package com.ls.controller.customer;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ls.config.satoken.SaTokenUtilPy;
import com.ls.controller.customer.model.*;
import com.ls.controller.user.model.LoginModel;
import com.ls.entity.Customer;
import com.ls.entity.SysUser;
import com.ls.service.ICustomerService;
import com.ls.utils.IpUtil;
import com.ls.utils.ResultData;
import com.ls.utils.login.CurrentUser;
import com.ls.utils.pay.TxtUtil;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ls.constant.SystemConstants.APP_TEST_PHONE;

/**
 * @ClassName CustomerAppController
 * @Description app用户控制器
 *
 * <p>
 * C端用户表 微信前端控制器
 * </p>
 *
 * @author pengyu
 * @since 2024-06-27
 */
@Api(value = "app用户相关接口", tags = "app用户相关接口")
@RestController
@RequestMapping("/customerApp")
@RequiredArgsConstructor
public class CustomerAppController {
    private final ICustomerService service;
    // 配置支持表单编码的RestTemplate
    private final RestTemplate restTemplate = new RestTemplate(
            Arrays.asList(
                    new FormHttpMessageConverter(),
                    new MappingJackson2HttpMessageConverter()
            )
    );
    public static String[] senIpList = new String[]{"221.6.*", "139.159.*", "119.3", "159.138.*", "120.133.*"};

    /** 更新个人信息  */
    @PostMapping(value = "updateOwnInfo")
    public ResultData updateOwnInfo(@Valid @RequestBody UpdateCustomerModel model) {
        return service.updateOwnInfo(model);
    }

    /** 设置是否平台签名   */
    @PostMapping(value = "setPlatformSign")
    public ResultData setPlatformSign(Integer isPlatformSign) {
        return service.setPlatformSign(isPlatformSign);
    }

    /** 设置签名  */
    @PostMapping(value = "setSign")
    public ResultData setSign(@Valid @RequestBody SetSignModel model) {
        return service.setSign(model);
    }
    /** 批量设置黑名单  */
    @PostMapping(value = "setBlackList")
    public ResultData setBlackList(@Valid @RequestBody List<String> phoneList) {
        return service.setBlackList(phoneList);
    }

    /**  批量取消黑名单  */
    @PostMapping(value = "cancelBlackList")
    public ResultData cancelBlackList(@Valid @RequestBody List<String> phoneList) {
        return service.cancelBlackList(phoneList);
    }

    /** 功能设置-发送通道 及 例外号码 channel_type */
    @PostMapping(value = "setChannelAndExceptList/{channelType}")
    public ResultData setChannelAndExceptList(@PathVariable("channelType") Integer channelType,@Valid @RequestBody List<String> phoneList) {
        return service.setChannelAndExceptList(channelType,phoneList);
    }

    /** 设置密码  */
    @PostMapping(value = "setPassword")
    public ResultData setPassword(@Valid @RequestBody SetPasswordModel setPasswordModel) {
        return service.setPassword(setPasswordModel);
    }
    /** 获取app当前登录用户信息  */
    @GetMapping(value = "/getUserInfo")
    public ResultData getUserInfo() {
        return service.getUserInfo();
    }
    /** 获取app当前用户签名  */
    @GetMapping(value = "/getUserSign")
    public ResultData getUserSign() {
        return service.getUserSign();
    }
    /** 头像上传  */
//    @PostMapping(value = "uploadAvatar")
//    public ResultData uploadAvatar(@Valid @RequestBody finlData avatar) {
//        return service.uploadAvatar();
//    }
    /** 查询当前风险状态 */
    @GetMapping(value = "getInfo")
    public ResultData getRisk(@RequestParam String phone,HttpServletRequest httpServletRequest) {
        boolean isInArea = true;
        String ip = IpUtil.getIpAddr(httpServletRequest);
        String location = "";
        if (phone.equals(APP_TEST_PHONE)){
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("isInArea", false);
            resultMap.put("ipLocation", location);
            return ResultData.successData(resultMap);
        }

        try {

            String url = "http://opendata.baidu.com/api.php?query=" + ip + "&co=&resource_id=6006&oe=utf8";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("ip", ip);
            map.add("key", "194e7dd959805967f66c4eb02a1a211e");
            JSONObject jsonObject = restTemplate.postForObject(url, new HttpEntity<>(map, headers), JSONObject.class);
//            String result = restTemplate.postForObject(url, new HttpEntity<>(map, headers), String.class);
//            JSONObject jsonObject = JSON.parseObject(result);
        } catch (Exception e) {
            isInArea = false;
        }

        Map<String, Object> resultMap = new HashMap<>();
        //false表示非安全区域，表示风险功能不能开发给用户
        resultMap.put("isInArea", isInArea&&!checkSensitiveIp(ip));
        resultMap.put("ipLocation", location);
        return ResultData.successData(resultMap);
    }
    /**
     * 检测用户是否为敏感用户
     *
     * @return true-敏感用户，false-非敏感用户
     */
    public Boolean checkSensitiveIp(String ip){
        // 判断ip号段是否在senIpList内
        if (!TxtUtil.isEmpty(ip)) {
            for (String senIpPattern : senIpList) {
                if (senIpPattern.endsWith("*")) {
                    // 处理通配符模式，如 "221.6.*"
                    String prefix = senIpPattern.substring(0, senIpPattern.length() - 1);
                    if (ip.startsWith(prefix)) {
                        return true;
                    }
                } else {
                    // 精确匹配或前缀匹配，如 "119.3"
                    if (ip.startsWith(senIpPattern)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

